package com.demo.crm.service;

import com.arvato.crm.model.FilterRule;
import com.arvato.crm.model.PagingInfo;
import com.arvato.crm.repository.NamedQueryTools;
import com.demo.crm.model.AjaxInfo;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.persistence.Query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author  fzd
 */
@Service
public class CouponsService {
    public Map<String,Object> couponsGrantPaging(final PagingInfo pagingInfo){

        final Query query=NamedQueryTools.createDynamicSqlQuery("couponsGrantList", new HashMap<String, Object>() {
            {
                List<FilterRule> rules=pagingInfo.getRules();
                if(CollectionUtils.isNotEmpty(rules)){
                    for(FilterRule rule:rules){
                        this.put(rule.getField(),rule.getValue());
                    }
                }
            }
        });
        final Query queryTotal=NamedQueryTools.createDynamicSqlQuery("couponsGrantListTotal", new HashMap<String, Object>() {
            {
                List<FilterRule> rules=pagingInfo.getRules();
                if(CollectionUtils.isNotEmpty(rules)){
                    for(FilterRule rule:rules){
                        this.put(rule.getField(),rule.getValue());
                    }
                }
            }
        });

        List<FilterRule> rules=pagingInfo.getRules();
        if(CollectionUtils.isNotEmpty(rules)){
            for(FilterRule rule:rules){
                if (StringUtils.isNotBlank(rule.getValue().toString())){
                    query.setParameter(rule.getField(),rule.getValue());
                    queryTotal.setParameter(rule.getField(),rule.getValue());
                }
            }
        }



        return new HashMap<String,Object>(){
            {
                this.put("total",Integer.parseInt(queryTotal.getSingleResult().toString()));
                this.put("rows",NamedQueryTools.queryForMap(query.setFirstResult((pagingInfo.getPage()-1) * pagingInfo.getRows()).setMaxResults(pagingInfo.getRows())));
            }
        };
    }
}
